package com.chap6;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * <code>ReentrantLockDemo</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-16 14:38
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
@Slf4j
public class ReentrantLockDemo3 {

    private static  final  ReentrantLock lock = new ReentrantLock(true);
    public static void main(String[] args) throws InterruptedException {


        for (int i = 0; i < 500; i++) {
            new Thread(()->{
                lock.lock();
                try {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.info(Thread.currentThread().getName()+"running...");
                }finally {
                    lock.unlock();
                }

            },"t"+i).start();

        }

        Thread.sleep(1000);

        //非公平，后面500个可以插队的
        //公平的，一定是上面500个线程执行完，后面500个才会执行
        for (int i = 0; i < 500; i++) {
            new Thread(()->{
                lock.lock();
                try {
                    log.info(Thread.currentThread().getName()+"running...");
                }finally {
                    lock.unlock();
                }

            },"强行插入"+i).start();

        }

    }
}

